package com.aube.rvi;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.aube.rvi.net.ImageLoader;
import com.aube.rvi.util.StringUtils;
import com.aube.rvi.util.Utils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by huyaonan on 16/10/25.
 */
public class BitmapCache implements ImageLoader.ImageCache {
    private LruCache<String, Bitmap> mCache;

    private static HashMap<String, Integer> mReferenceIndicator = new HashMap();

    public BitmapCache() {
        int maxSize = (int) (Runtime.getRuntime().maxMemory() / 8);
        mCache = new LruCache(maxSize);
    }

    private void updateReference(String url) {
        if (mReferenceIndicator == null)
            mReferenceIndicator = new HashMap<>();
        if (mReferenceIndicator.containsKey(url)) {
            int num = mReferenceIndicator.get(url);
            mReferenceIndicator.put(url, ++num);
        } else {
            mReferenceIndicator.put(url, 1);
        }
    }

    @Override
    public Bitmap getBitmap(String url) {
        updateReference(url);//有引用+1
        return mCache.get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        mCache.put(url, bitmap);
        updateReference(url);//存数据也+1
    }

    @Override
    public void clear() {
        if (mCache != null)
            mCache.evictAll();
        if (mReferenceIndicator != null)
            mReferenceIndicator.clear();
    }

    @Override
    public void releaseBitmap(String url) {
        if (mCache != null)
            mCache.remove(url);
    }

}
